package com.common.hbase.instance;


import com.common.hbase.config.HbaseConfig;
import com.common.hbase.domain.*;
import com.common.hbase.liaison.HbaseInterface;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class HbaseInstance {

    // 行键前缀固定长度，不足的用0补齐（后补）
    private static final int ROW_KEY_PRE_LENGTH = 40;
    // 行键参数固定长度，不足用0补齐（前补）
    private static final int ROW_KEY_OPTIONS_LENGTH = 100;
    // 行键前缀固定长度，不足的用0补齐（前补）
    private static final int ROW_KEY_SUF_LENGTH = 40;


    private Configuration conf = HBaseConfiguration.create();
    private Connection conn = null;
    private Admin admin = null;

    private static final Logger log = LoggerFactory.getLogger(HbaseInstance.class);

    /*
    *  配置 hbase
    * */
    public HbaseInstance(HbaseConfig hbaseConfig) {
        Map<String, String> confMaps = hbaseConfig.getConfMaps();
        confMaps.forEach((key,val) -> {
            conf.set(key,val);
        });
        try {
            conn = ConnectionFactory.createConnection(conf);
            admin = conn.getAdmin();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    *  根据表名判断表是否存在
    * */
    public boolean isTableExist(String tableName){
        /*
         *  获取配置信息
         * */
        TableName tableName1 = TableName.valueOf(tableName);
        boolean b = false;
        try {
            b = admin.tableExists(tableName1);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return b;
    }

    /*
    *  创建表
    * */
    public boolean createTable(CreateDomain createDomain){
        if (createDomain==null){
            log.info("CreateDomain  not  null");
            return false;
        }
        if (isTableExist(createDomain.getTableName())){
            log.info(createDomain.getTableName()+"表以存在");
            return false;
        }
        HTableDescriptor hTableDescriptor = createDomain.getHTableDescriptor();
        try {
            admin.createTable(hTableDescriptor);
            log.info(createDomain.getTableName()+"创建成功");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /*
    *  删除表
    * */
    public boolean deleteTable(String tableName){
        if (!isTableExist(tableName)){
            log.info(tableName+"表不存在");
            return false;
        }

        try {
            admin.disableTable(TableName.valueOf(tableName));
            admin.deleteTable(TableName.valueOf(tableName));
            log.info(tableName+"删除成功");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /*
    *  添加数据
    * */
    public boolean put(PutDomain putDomain){
        Table table = null;
        try {
            table = conn.getTable(TableName.valueOf(putDomain.getTableName()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (table==null){
            log.info("找不到表"+putDomain.getTableName());
            return false;
        }else{
            try {
                table.put(putDomain.getPut());
                table.close();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /*
    *  批量添加数据
    * */
    public boolean puts(HbaseInterface hbaseInterface){
        if (hbaseInterface==null){
            System.out.println("HbaseInterface  Not Null");
            log.info("HbaseInterface  Not Null");
            return false;
        }
        try {
            if (!isTableExist(hbaseInterface.getTableName())){
                createTable(hbaseInterface.getCreateTable());
            }
            for (PutDomain putDomain : hbaseInterface.getPutDomains()) {
                put(putDomain);
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /*
    *  get 查询
    * */
    public Cell[] getTable(GetDomain getDomain){

        try {
            Table table = null;

            table = conn.getTable(TableName.valueOf(getDomain.getTableName()));

            if (table!=null){
                Result result = table.get(getDomain.getGet());
                Cell[] cells = result.rawCells();
                table.close();
                return cells;
            }
        } catch (IOException e) {
            if (getDomain==null){
                log.info("GetDomain  not  null");
            }
            if (!getDomain.getTableName().isEmpty()){
                log.info(getDomain.getTableName()+"   表未找到");
                System.out.println(getDomain.getTableName()+"   表未找到");
            }else{
                log.info("表名不能为空");
            }
        }
        return null;
    }

    /*
    *  自定义get查询
    * */
    public Cell[] getTable(HbaseInterface hbaseInterface){
        return getTable(hbaseInterface.getGetDomain());
    }

    /*
    *  scan查询
    * */
    public ResultScanner scanTable(ScanDomain scanDomain){

        try {
            Table table = null;

            table = conn.getTable(TableName.valueOf(scanDomain.getTableName()));
            if (table!=null){
                ResultScanner scanner = table.getScanner(scanDomain.getScan());
                return scanner;
            }
        } catch (IOException e) {
            if (scanDomain==null){
                log.info("ScanDomain  not  null");
            }
            if (!scanDomain.getTableName().isEmpty()){
                log.info(scanDomain.getTableName()+"   表未找到");
                System.out.println(scanDomain.getTableName()+"   表未找到");
            }else{
                log.info("表名不能为空");
            }
        }
        return null;
    }

    /*
    *  自定义scan查询
    * */
    public ResultScanner scanTable(HbaseInterface hbaseInterface){
        return scanTable(hbaseInterface.getScanDomain());
    }


}
